<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * HITI Web Develop
 *
 * @package     HITI Web Dev
 * @category    Controllers
 * @see 		Hiti Ajax
 * @author      PHUOCNGUYEN - HITI Dev Team
 * @copyright   Copyright (c) 2013, HITI Corp
 */

class Hiti_ajax extends CI_Controller {
	public function __construct()
	{
		parent::__construct();
		if (!$this->input->is_ajax_request())
		{
		   exit('No direct script access allowed');
		}
		/*
		* Load ajax model
		*/
		$this->load->model('hiti_common_model', 'hiti', true);
		$this->hiti->hiti_init();
		$this->load->model('hiti_ajax_model', 'ajax', true);
	}

	public function set_language()
	{
		$lng = $this->input->post('lng', true);
		$this->session->set_userdata(array('lng' => $lng));
	}

	public function add_comment()
	{
		$email = $this->input->post('email', true);
		$date = date('Y-m-d H:i:s');
		$time = time();
		$check = get_data('comments', "`deleted` = 0 AND `email` = '$email'", "date_added", 0, 1, "id DESC");
		$check = strtotime($check);
		$timelimit = round(($time - $check));
		$json = array(
			'status'	=> '',
			'date' 		=> $date,
			'limit'		=> $timelimit
		);
		if($timelimit > 10){
			$data = array(
				'email' => $email,
				'name' => $this->input->post('name', true),
				'product' => $this->input->post('product', true),
				'info' => $this->input->post('info', true),
				'ip' => $this->input->ip_address(),
				'date_added' => $date
			);
			if ($this->ajax->add_comment($data))
			{
				$json['status']	= 1;
			}
			else
			{
				echo '';
			}
		} else {
			$json['status']	= 0;
		}
		echo json_encode($json);
	}

	public function add_contact()
	{
		$name = $this->input->post('name', true);
		$email = $this->input->post('email', true);
		$name = $name ? $name : $email;
		$data = array(
			'name_vn' => $name,
			'email' => $email,
			'address' => $this->input->post('address', true),
			'company' => $this->input->post('company', true),
			'title' => $this->input->post('title', true),
			'phone' => $this->input->post('phone', true),
			'content' => $this->input->post('content', true),
			'date_added' => date('Y-m-d H:i:s'),
			'ip' => $this->input->ip_address()
		);
		if ($this->ajax->add_contact($data))
		{
			$config = array(
				'protocol' => 'smtp',
		        'smtp_host' => $GLOBALS['cfg']['smtp_host'],
		        'smtp_port' => $GLOBALS['cfg']['smtp_port'],
		        'smtp_user' => $GLOBALS['cfg']['smtp_user'],
		        'smtp_pass' => $GLOBALS['cfg']['smtp_pass'],
		        'mailtype'  => 'html',
		        'charset' => 'utf8',
		        'wordwrap' => TRUE
		    );
			  $this->load->library('email',$config);
		      $this->email->set_newline("\r\n");
		      $this->email->from($GLOBALS['cfg']['smtp_mailer']); // change it to yours
		      $this->email->to($GLOBALS['cfg']['contact_email']);// change it to yours
		      $this->email->subject('Xác nhận đơn hàng');
		      $this->email->message($data['name_vn']);
		    if($this->email->send())
		    {
		    	echo "1";
		    }
		     else
		      {
		     	show_error($this->email->print_debugger());
		      }	
			//echo 1;
			 //  $config = array(
			 //  'protocol' => 'smtp',
			 //  'smtp_host' => 'ssl://smtp.googlemail.com',
			 //  'smtp_port' => 465,
			 //  'smtp_user' => 'kimduong.basa@gmail.com', // change it to yours
			 //  'smtp_pass' => 'kimduongbasa123', // change it to yours
			 //  'mailtype' => 'html',
			 //  'charset' => 'utf8',
			 //  'wordwrap' => TRUE
			 //  );
			 
		  //     $this->load->library('email',$config);
		  //     $this->email->set_newline("\r\n");
		  //     $this->email->from('kimduong.basa@gmail.com'); // change it to yours
		  //     $this->email->to('lmtuyen2811@gmail.com');// change it to yours
		  //     $this->email->subject('Xác nhận đơn hàng');
		  //     $this->email->message($data['name_vn']);
			 // // $this->email->attach();
		  //     if($this->email->send())
		  //     {
		  //    	echo "Email sent";
		  //     }
		  //     else
		  //     {
		  //    	show_error($this->email->print_debugger());
		  //     }	
		}
		return false;
	}

	public function add_cart()
	{
		$id = $this->input->post('id', true);
		$sl = $this->input->post('sl', true);
		if (!is_numeric($id) || $id == 0)
		{
			echo 0;
			return false;
		}
		$color = $this->input->post('color', true);
		$kthuoc = $this->input->post('kthuoc', true);
		echo $this->ajax->add_cart($id, $sl, $color, $kthuoc);
		return false;
	}

	public function remove_cart()
	{
		$id = $this->input->post('id', true);
		if (!is_numeric($id) || $id == 0)
		{
			echo 0;
			return false;
		}
		echo $this->ajax->remove_cart($id);
		return false;
	}

	public function shopping_cart()
	{
		$this->load->model('hiti_carts_model', 'cart', true);
		$carts = $this->cart->show();
		$content = '';
		$total = 0;
		if (is_array($carts) && count($carts))
		{
			foreach ($carts as $data)
			{
				$data['thanhtien'] = $data['gia'] * $data['soluong'];
                $total += $data['thanhtien'];
                $content .= $this->load->view('home/item_cart', $data, true);
			}
		}
		$numCart = $this->ajax->num_cart();
		$data = array(
	        'numCart' => $numCart,
	        'total' => number_format($total),
	        'content' => $content,
	    );
		echo json_encode($data);
		return false;
	}

	public function update_cart()
	{
		$id = $this->input->post('id', true);
		if (!is_numeric($id) || $id == 0)
		{
			echo 0;
			return false;
		}
		$qty = $this->input->post('qty', true);
		echo $this->ajax->update_cart($id, $qty);
		return false;
	}

	public function empty_cart()
	{
		$this->ajax->empty_cart();
		echo 1;
		return false;
	}

	public function add_subscriber()
	{
		if (!$_POST)
		{
			echo '';
			return false;
		}
		$email = $this->input->post('email', true);
		if (!$email)
		{
			echo '';
			return false;
		}
		if ($this->ajax->check_email_exists($email, 'subscribers'))
		{
			echo 0;
			return false;
		}
		$data = array(
			'sex' => $this->input->post('sex', true),
			'email' => $email,
			'city' => $this->input->post('city', true),
			'date_added' => date('Y-m-d H:i:s'),
			'ip' => $this->input->ip_address()
		);
		if ($this->ajax->add_subscriber($data))
		{
			echo 1;
		}
		return false;
	}

	public function add_member()
	{
		$email = $this->input->post('email', true);
		if (!$email)
		{
			echo '';
			return false;
		}
		$data = array(
			'name' => $this->input->post('name', true),
			'password' => md5($this->input->post('password', true)),
			'email' => $email,
			'diachi_lienhe' => $this->input->post('diachi_lienhe', true),
			'gioitinh' => $this->input->post('gioitinh', true),
			'thanhpho' => $this->input->post('thanhpho', true),
			'dienthoai' => $this->input->post('dienthoai', true),
			'ngay' => $this->input->post('ngay', true),
			'thang' => $this->input->post('thang', true),
			'nam' => $this->input->post('nam', true),
			'date_added' => date('Y-m-d H:i:s'),
			'ip' => $this->input->ip_address()
		);
		if ($this->ajax->add_member($data))
		{
			$session = array(
                'mem_logged' => true,
                'token' => md5(uniqid(rand(), TRUE)),
                'mem_email' => $email
            );
            $this->session->set_userdata($session);
			setcookie('mem_logged', 1, time() + COOKIE_TIME, '/');
			setcookie('mem_email', $email, time() + COOKIE_TIME, '/');
			echo 1;
		}
		return false;
	}

	public function login()
	{
		$email = $this->input->post('email', true);
		if (!$email)
		{
			echo 0;
			return false;
		}
		$password = md5($this->input->post('password', true));
		$mem_name = $this->ajax->login($email, $password);
		if (is_array($mem_name))
		{
			$session = array(
                'mem_logged' => true,
                'token' => md5(uniqid(rand(), TRUE)),
                'mem_email' => $email
            );
            $this->session->set_userdata($session);
			setcookie('mem_logged', 1, time() + COOKIE_TIME, '/');
			setcookie('mem_email', $email, time() + COOKIE_TIME, '/');
			$data = array(
				'online_lastactive' => time(),
				'last_login' => date('Y-m-d H:i:s'),
				'ip' => $this->input->ip_address()
			);
			$this->ajax->save_profile($data);
			echo json_encode(array('avartar' => $mem_name['avartar'], 'name' => end(explode(' ', $mem_name['name']))));
		}
		else
		{
			echo 0;
		}
		return false;
	}

	public function save_profile()
	{
		$data = array(
			'name' => $this->input->post('name', true),
			'diachi_lienhe' => $this->input->post('diachi_lienhe', true),
			'gioitinh' => $this->input->post('gioitinh', true),
			'thanhpho' => $this->input->post('thanhpho', true),
			'dienthoai' => $this->input->post('dienthoai', true),
			'ngay' => $this->input->post('ngay', true),
			'thang' => $this->input->post('thang', true),
			'nam' => $this->input->post('nam', true),
			'date_modified' => date('Y-m-d H:i:s')
		);
		$password = $this->input->post('password', true);
		if ($password) $data['password'] = md5($password);
		if ($this->ajax->save_profile($data))
		{
			echo 1;
		}
		return false;
	}

	public function check_email_exists()
	{
		$email = $this->input->post('email', true);
		if (!$email)
		{
			echo 1;
			return false;
		}
		echo $this->ajax->check_email_exists($email);
		return false;
	}

	public function show_login()
	{
		$fblogin_url = 'https://www.facebook.com/dialog/oauth?client_id='.$GLOBALS['cfg']['facebook_app_id'].'&redirect_uri='.urlencode(base_url()).'&state='.$this->session->userdata('fb_state').'&scope=user_birthday,email,user_mobile_phone,user_address';
		$data = array(
			'fblogin_url' => $fblogin_url
		);
		$this->load->view('home/login', $data);
	}

	public function show_register()
	{
		$fblogin_url = 'https://www.facebook.com/dialog/oauth?client_id='.$GLOBALS['cfg']['facebook_app_id'].'&redirect_uri='.urlencode(base_url()).'&state='.$this->session->userdata('fb_state').'&scope=user_birthday,email,user_mobile_phone,user_address';
		$data = array(
			'region_list' => $this->hiti->region_list(),
			'fblogin_url' => $fblogin_url
		);
		$this->load->view('home/register', $data);
	}

	public function show_profile()
	{
		$data = array(
			'info' => $this->hiti->profile(),
			'region_list' => $this->hiti->region_list()
		);
		$data['info']['avartar'] = $data['info']['avartar'] ? 'upload/avatars/'.$data['info']['avartar'] : 'images/avanam.jpg';
		$this->load->view('home/profile', $data);
	}

	public function load_city()
	{
		$show = $this->input->post('show', 1);
		if($show)
		{
			$parent = $this->input->post('parent', true);
	        $i = 0;
	        $cities = $this->ajax->load_city($parent);
	        if (count($cities) && is_array($cities))
	        {
	        	foreach ($cities as $data)
	        	{
	            	$obj[$i++] = $data;
	            }
	        }
	        echo json_encode($obj);
	    }
		return false;
	}

	public function hoantat_hoadon()
	{
		$mamua = $this->input->post('orders_code', true);
		if (!$mamua)
		{
			echo 0;
			return false;
		}
		$maxacthuc = randomkeys(6);
		$ngaydat = date('Y-m-d H:i:s');
		$tongcong = $this->input->post('tongcong', true);
		$tien_thanhtoan = $this->input->post('tien_thanhtoan', true);
		$data = array(
			'ten_nguoimua' => $this->input->post('ten_nguoimua', true),
			'dienthoai_nguoimua' => $this->input->post('dienthoai_nguoimua', true),
			'diachi_giaohang' => $this->input->post('diachi_giaohang', true),
			'phuongthuc_thanhtoan' => $this->input->post('phuongthuc_thanhtoan', true),
			'email_nguoimua' => $this->input->post('email_nguoimua', true),
			'tongcong' => $tongcong,
			'khachhang_ghichu' => $this->input->post('khachhang_ghichu', true),
			'tien_thanhtoan' => $tien_thanhtoan,
			'address_city' => $this->input->post('address_city', true),
            'address_district' => $this->input->post('address_district', true),
            'address_ward' => $this->input->post('address_ward', true),
            'phi_giaohang' => $this->input->post('phi_giaohang', true),
            'vat' => $this->input->post('vat', true),
            'congty' => $this->input->post('congty', true),
			'diachi_congty' => $this->input->post('diachi_congty', true),
			'masothue' => $this->input->post('masothue', true),
			'maxacthuc' => $maxacthuc,
			'ma' => $mamua,
			'status' => 0,
			'ip' => $this->input->ip_address(),
			'date_added' => $ngaydat
		);
		$this->ajax->hoantat_hoadon($data);
		$this->load->model('hiti_carts_model', 'cart', true);
		$order = $this->cart->info($mamua);
		$carts = $this->cart->details($mamua);
		if ($data['phuongthuc_thanhtoan'] == 2)
		{
			$items_str = '';
			$i = 0;
			$subtotal = 0;
			foreach ($carts as $cart)
			{
				$itemtotal = vnd2usd($cart['gia']) * $cart['soluong'];
				$subtotal += $itemtotal;
				$items_str .= '&L_NAME'.$i.'='.urlencode($cart['name']).'&L_NUMBER'.$i.'='.($i+1).'&L_DESC'.$i.'='.urlencode($cart['code']).'&L_AMT'.$i.'='.urlencode(vnd2usd($cart['gia'])).'&L_QTY'.$i.'='.(int)$cart['soluong'].'';
				$i++;
			}
			$vat = 0;
			if ($order['vat']) $vat = $subtotal * 0.1;
	        $ship = vnd2usd($order['phi_giaohang']);
	        $total = $subtotal + $vat + $ship;
			$return = base_url().'don-hang/'.$mamua.'?paypal=success';
			$cancel = base_url().'don-hang/'.$mamua.'?paypal=cancel';
			$logo = base_url().'images/logo.png';
			$httpResponseArray = paypal_setexpress($mamua, $subtotal, $vat, $ship, $total, $items_str, $return, $cancel, $logo);
			if (is_array($httpResponseArray) && count($httpResponseArray))
			{
				$order['linkxacthuc'] = 0;
				$mail_subj = $GLOBALS['lng']['invoices_paid_paypal'];
				echo $GLOBALS['cfg']['paypal_url'].'?cmd=_express-checkout&token='.urldecode($httpResponseArray['TOKEN']).'&useraction=commit';
			}
			else
			{
				$order['linkxacthuc'] = 1;
				$mail_subj = $GLOBALS['lng']['confirm_order'];
				echo 0;
			}
		}
		else if ($data['phuongthuc_thanhtoan'] == 3)
		{
			$return = base_url().'don-hang/'.$mamua.'?nganluong=success';
			$order['linkxacthuc'] = 0;
			$mail_subj = $GLOBALS['lng']['invoices_paid_nganluong'];
			echo nganluong_getrequesturl($mamua, $order['tien_thanhtoan'], '', $return);
		}
		else if ($data['phuongthuc_thanhtoan'] == 4)
		{
			$return = base_url().'don-hang/'.$mamua.'?baokim=success';
			$cancel = base_url().'don-hang/'.$mamua.'?baokim=cancel';
			$order['linkxacthuc'] = 0;
			$mail_subj = $GLOBALS['lng']['invoices_paid_baokim'];
			echo baokim_createrequesturl($mamua, $order['tien_thanhtoan'], $order['phi_giaohang'], $order['vat'], $return, $cancel);
		}
		else if ($data['phuongthuc_thanhtoan'] == 5)
		{
			$return = base_url().'don-hang/'.$mamua.'?sohapay=success';
			$order['linkxacthuc'] = 0;
			$mail_subj = $GLOBALS['lng']['invoices_paid_sohapay'];
			echo sohapay_buildcheckouturl($mamua, $order['tien_thanhtoan'], '', $data['email_nguoimua'], $data['dienthoai_nguoimua'], $return);
		}
		else
		{
			$order['linkxacthuc'] = 1;
			$mail_subj = $GLOBALS['lng']['confirm_order'];
		}
		$mail_mess = '';
		if ($order)
		{
			$home = array(
				'info' => $order,
				'carts' => $this->cart->details($mamua)
			);
			$mail_mess = $this->load->view('home/order_printer', $home, true);
		}
		$config = array(
			'protocol' => 'smtp',
	        'smtp_host' => $GLOBALS['cfg']['smtp_host'],
	        'smtp_port' => $GLOBALS['cfg']['smtp_port'],
	        'smtp_user' => $GLOBALS['cfg']['smtp_user'],
	        'smtp_pass' => $GLOBALS['cfg']['smtp_pass'],
	        'mailtype'  => 'html',
	        'charset' => 'utf8',
	        'wordwrap' => TRUE
	    );
	 //    $this->load->library('email', $config);
		// $this->email->clear();
	 //    $this->email->from($GLOBALS['cfg']['smtp_mailer']);
	  $this->load->library('email',$config);
      $this->email->set_newline("\r\n");
      $this->email->from($GLOBALS['cfg']['smtp_mailer']);
	    $this->email->to($data['email_nguoimua']);
	    $this->email->subject($mail_subj);
	    $this->email->message($mail_mess);
	    if ($this->email->send())
	    {

	    }
	    else
	    {

	    }
		return false;
	}

	public function order_confirm()
	{
		$ma = $this->input->post('ma', true);
		$maxacthuc = $this->input->post('maxacthuc', true);
		if (!$ma || !$maxacthuc)
		{
			echo 0;
			return false;
		}
		echo $this->ajax->order_confirm($ma, $maxacthuc);
		return false;
	}

}

/* End of file hiti_ajax.php */
/* Location: ./application/controllers/hiti_ajax.php */